package com.insurance.modules.claim.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.insurance.common.utils.AmountUtils;
import com.insurance.common.utils.PageUtils;
import com.insurance.common.utils.Query;
import com.insurance.modules.claim.constants.ClaimConstants;
import com.insurance.modules.claim.constants.EntityTypeEnum;
import com.insurance.modules.claim.dao.SettlementAmountDao;
import com.insurance.modules.claim.entity.ClaimCaseEntity;
import com.insurance.modules.claim.entity.ClaimSettlementEntity;
import com.insurance.modules.claim.entity.FileInfoEntity;
import com.insurance.modules.claim.entity.SettlementAmountEntity;
import com.insurance.modules.claim.service.*;
import com.insurance.modules.claim.vo.request.SettlementAmountSaveReq;
import com.insurance.modules.claim.vo.response.SettlementAmountRsp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service("settlementAmountService")
public class SettlementAmountServiceImpl extends ServiceImpl<SettlementAmountDao, SettlementAmountEntity> implements SettlementAmountService {
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private ClaimSettlementService claimSettlementService;
    @Autowired
    private ClaimCaseService claimCaseService;
    @Autowired
    private SettlementAmountService settlementAmountService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SettlementAmountEntity> page = this.page(
                new Query<SettlementAmountEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public SettlementAmountRsp getByCsId(String csId) {
        LambdaQueryWrapper<SettlementAmountEntity> settlementQueryWrapper = Wrappers.lambdaQuery();
        settlementQueryWrapper.eq(SettlementAmountEntity::getCsId, csId);
        SettlementAmountEntity settlementAmount = this.getOne(settlementQueryWrapper);
        if (settlementAmount == null) {
            return new SettlementAmountRsp();
        }
        // 金额分转元
        SettlementAmountRsp rsp = new SettlementAmountRsp();
        rsp.setId(settlementAmount.getId());
        rsp.setCsId(csId);
        rsp.setDeathAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getDeathAmount()));
        rsp.setDisabilityAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getDisabilityAmount()));
        rsp.setTreatmentAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getTreatmentAmount()));
        rsp.setDelayWorkAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getDelayWorkAmount()));
        rsp.setDisabilityAppraisalAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getDisabilityAppraisalAmount()));
        rsp.setDisabilityAppraisalLevel(settlementAmount.getDisabilityAppraisalLevel());
        rsp.setPublicAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getPublicAmount()));
        rsp.setEmployerAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getEmployerAmount()));
        rsp.setThirdAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getThirdAmount()));
        rsp.setOtherAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getOtherAmount()));
        rsp.setTotalAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getTotalAmount()));
        rsp.setApplyAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getApplyAmount()));
        rsp.setSelfAmountYuan(AmountUtils.fenToYuanBigDecimal(settlementAmount.getSelfAmount()));
        rsp.setRemark(settlementAmount.getRemark());
        rsp.setPayTime(settlementAmount.getPayTime());
        rsp.setFiles(fileInfoService.listByBusinessIdAndAttachment(csId, null, EntityTypeEnum.settlementAmount));
        return rsp;
    }

    @Override
    @Transactional
    public void saveSettlementAmountAndFile(SettlementAmountSaveReq req) {
        saveOrUpdateSettlementAmount(req);
        // 保存结案金额相关的文件
        List<FileInfoEntity> files = req.getFiles();
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(files)){
            for (FileInfoEntity file : files) {
                file.setBusinessId(req.getCsId());
                file.setCreateTime(req.getUpdateTime());
                file.setCreateBy(req.getUpdateBy());
            }
            //批量保存
            fileInfoService.saveBatch(files);
        }
        List<String> deleteFiles = req.getDeleteFiles();
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(deleteFiles)){
            //根据id批量删除
            fileInfoService.removeByIds(deleteFiles);
        }
    }

    /**
     * 保存结案金额信息
     */
    private void saveOrUpdateSettlementAmount(SettlementAmountSaveReq req) {
        // 金额元转分
        SettlementAmountEntity settlementAmount = new SettlementAmountEntity();
        settlementAmount.setId(req.getId());
        settlementAmount.setCsId(req.getCsId());
        settlementAmount.setDeathAmount(AmountUtils.yuanToFenLong(req.getDeathAmountYuan()));
        settlementAmount.setDisabilityAmount(AmountUtils.yuanToFenLong(req.getDisabilityAmountYuan()));
        settlementAmount.setTreatmentAmount(AmountUtils.yuanToFenLong(req.getTreatmentAmountYuan()));
        settlementAmount.setDelayWorkAmount(AmountUtils.yuanToFenLong(req.getDelayWorkAmountYuan()));
        settlementAmount.setDisabilityAppraisalAmount(AmountUtils.yuanToFenLong(req.getDisabilityAppraisalAmountYuan()));
        settlementAmount.setDisabilityAppraisalLevel(req.getDisabilityAppraisalLevel());
        settlementAmount.setPublicAmount(AmountUtils.yuanToFenLong(req.getPublicAmountYuan()));
        settlementAmount.setEmployerAmount(AmountUtils.yuanToFenLong(req.getEmployerAmountYuan()));
        settlementAmount.setThirdAmount(AmountUtils.yuanToFenLong(req.getThirdAmountYuan()));
        settlementAmount.setOtherAmount(AmountUtils.yuanToFenLong(req.getOtherAmountYuan()));
        settlementAmount.setTotalAmount(AmountUtils.yuanToFenLong(req.getTotalAmountYuan()));
        settlementAmount.setApplyAmount(AmountUtils.yuanToFenLong(req.getApplyAmountYuan()));
        settlementAmount.setSelfAmount(AmountUtils.yuanToFenLong(req.getSelfAmountYuan()));
        settlementAmount.setPayTime(req.getPayTime());
        settlementAmount.setRemark(req.getRemark());
        if(null == req.getId()){
            settlementAmount.setCreateBy(req.getCreateBy());
            settlementAmount.setCreateTime(req.getCreateTime());
        }
        settlementAmount.setUpdateBy(req.getUpdateBy());
        settlementAmount.setUpdateTime(req.getUpdateTime());
        this.saveOrUpdate(settlementAmount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finishCase(SettlementAmountSaveReq req) {
        // 1.保存结案金额及相关文件
        settlementAmountService.saveSettlementAmountAndFile(req);
        // 2.修改理赔状态-
        settlementAmountService.updateCaseStatus2Commit(req.getCsId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void litigation(SettlementAmountSaveReq req) {
        ClaimSettlementEntity claimSettlement = claimSettlementService.getById(req.getCsId());
        if(claimSettlement.getCaseStatus().intValue() != ClaimConstants.CLAIM_STATUS_COMMIT){
            return;
        }
        ClaimSettlementEntity upEntity = new ClaimSettlementEntity();
        upEntity.setId(req.getCsId());
        upEntity.setCaseStatus(ClaimConstants.CLAIM_STATUS_LITIGATION);
        claimSettlementService.updateById(upEntity);
        ClaimSettlementEntity settlementEntity = claimSettlementService.getById(req.getCsId());
        ClaimCaseEntity entity = new ClaimCaseEntity();
        entity.setId(settlementEntity.getCaseId());
        entity.setCaseStatus(ClaimConstants.CASE_STATUS_LITIGATION);
        if(settlementEntity.getSettlementOrder().intValue() == ClaimConstants.SETTLEMENT_ORDER_FIRST){
            entity.setFirstStatus(ClaimConstants.CLAIM_STATUS_LITIGATION);
        }else{
            entity.setSecondStatus(ClaimConstants.CLAIM_STATUS_LITIGATION);
        }
        claimCaseService.updateById(entity);
    }

    /**
     * 案件理赔表理赔记录的状态为已提交保司（case_status = 2）时：
     *  1.非外包人员 --> 已结案已打款（case_status = 4）
     *  2.外包人员 --> 已结案未打款（case_status = 3）
     * @param csId
     */
    @Override
    @Transactional
    public void updateCaseStatus2Commit(String csId) {
        ClaimSettlementEntity claimSettlement = claimSettlementService.getById(csId);
        if (ClaimConstants.CLAIM_STATUS_COMMIT.equals(claimSettlement.getCaseStatus())
                || ClaimConstants.CLAIM_STATUS_LITIGATION.equals(claimSettlement.getCaseStatus())) {
            int newCaseStatus = ClaimConstants.CLAIM_STATUS_FINISH;
            // 更新案件理赔表
            claimSettlement.setCaseStatus(newCaseStatus);
            claimSettlementService.updateById(claimSettlement);

            // 更新案件表冗余状态
            LambdaUpdateWrapper<ClaimCaseEntity> claimCaseUpdateWrapper = Wrappers.lambdaUpdate();
            claimCaseUpdateWrapper.eq(ClaimCaseEntity::getId, claimSettlement.getCaseId());
            if (ClaimConstants.SETTLEMENT_ORDER_FIRST.equals(claimSettlement.getSettlementOrder())) {
                // 首次理赔
                claimCaseUpdateWrapper.set(ClaimCaseEntity::getFirstStatus, newCaseStatus);
            } else {
                // 二次理赔
                claimCaseUpdateWrapper.set(ClaimCaseEntity::getSecondStatus, newCaseStatus);
            }
            //案件状态同步更改
            claimCaseUpdateWrapper.set(ClaimCaseEntity::getCaseStatus, ClaimConstants.CASE_STATUS_FINISH);
            claimCaseService.update(claimCaseUpdateWrapper);
        }
    }


}
